from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QMessageBox, QTreeWidgetItem, QPushButton, QHBoxLayout, QWidget, QVBoxLayout

from src.main.server.controller.score_controller import ScoreController
from src.main.server.controller.server_feedback_controller import ServerFeedbackController
from src.main.server.controller.server_info_controller import ServerInfoController
from src.main.server.controller.server_review_controller import ServerReviewController
from src.main.server.controller.vol_info_controller import VolInfoController
from src.main.vision.windows.add_server_project_window import add_server_project_window
from src.main.vision.windows.client_login_window import client_login_window
from src.main.vision.windows.edit_feedback_window import edit_feedback_window
from src.main.vision.windows.edit_review_window import edit_review_window
from src.main.vision.windows.edit_score_window import edit_score_window
from src.main.vision.windows.edit_vol_info_window import edit_vol_info_window


class MainUiLoader:
    def __init__(self, controller=None):
        self.ui_file_path = "../../../qt_ui/main_window.ui"
        self.window = None
        self.controller = controller
        self._load_ui()

    def _load_ui(self):
        file = QFile(self.ui_file_path)
        try:
            self.window = QUiLoader().load(file)

            self.new_data()
            self.show_graph()

            self.window.pushButton_2.clicked.connect(self.operator_server_project_window) # 展示新增项目窗口
            self.window.pushButton.clicked.connect(self.show_confirmation_dialog) # 按钮提示框
            self.window.pushButton_3.clicked.connect(self.show_client_login_window)
            self.window.pushButton_4.clicked.connect(self.new_data)  #刷新数据


        finally:
            file.close()

    def show_graph(self):
        pass

    def show_client_login_window(self):
        """进入模拟的用户登录界面"""
        client_login_window(self)

    def new_data(self):
        """刷新数据：刷新前先清空已有数据"""
        # 清空所有 treeWidget 的现有内容
        print("页面数据刷新啦~~~")
        self.window.treeWidget.clear()
        self.window.treeWidget_2.clear()
        self.window.treeWidget_3.clear()
        self.window.treeWidget_4.clear()
        self.window.treeWidget_5.clear()

        # 重新加载数据
        self.show_volunteers_info_data()  # 展示全部志愿者信息
        self.show_server_project_data()  # 展示全部项目数据
        self.show_review_data()  # 展示全部审核信息
        self.show_feedback_data()  # 展示所有反馈信息
        self.show_score_data()  # 展示所有积分记录信息

    def checkout_login_window(self):
        print("进入登录UI")
        self.window.close()
        if self.controller:
            self.controller.show_login()

    def operator_server_project_window(self):
        """新增项目的小窗口，作为独立窗口展示"""
        add_server_project_window(self, "新增项目")


    def show_confirmation_dialog(self):
        """按钮提示框"""
        reply = QMessageBox.question(
            self.window,
            "确认",
            "是否确定执行此操作？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            print("用户选择退出登录")
            self.checkout_login_window()
        else:
            print("用户取消退出登录")


    def show_server_project_data(self):
        """项目发布"""
        def edit(fd, sd):
            data = ServerInfoController().get_info(fd, sd)
            add_server_project_window(self, "编辑项目", data)

        def window_delete(fd, sd):
            print("我被触发啦")
            ServerInfoController().delete(fd, sd)
            self.new_data() #刷新页面数据

        server_info_data = ServerInfoController().all_info()
        self.common_data(edit, server_info_data, self.window.treeWidget_2, delete_func=window_delete)

    def show_volunteers_info_data(self):
        """志愿者信息管理"""
        def edit(fd, sd):
            data = VolInfoController().get_info(fd, sd)
            edit_vol_info_window(self,data)

        def window_delete(fd, sd):
            print("我被触发啦")
            VolInfoController().delete(fd)
            self.new_data()

        vol_info_data = VolInfoController().all_info()
        self.common_data(edit, vol_info_data, self.window.treeWidget, delete_func=window_delete)

    def show_review_data(self):
        """志愿者报名与审核"""
        def edit(fd, sd):
            data = ServerReviewController().get_info(fd, sd)
            edit_review_window(self, data)

        def window_delete(fd, sd):
            print("我被触发啦")
            QMessageBox.information(self.window, "提示", "未提供删除功能，敬请期待")

        server_review_data = ServerReviewController().all_info()
        self.common_data(edit, server_review_data, self.window.treeWidget_3, delete_func=window_delete)
    def show_feedback_data(self):
        """服务过程管理"""
        def edit(fd, sd):
            data = ServerFeedbackController().get_info((fd, sd))
            edit_feedback_window(self, data)

        def window_delete(fd, sd):
            print("我被触发啦")
            QMessageBox.information(self.window, "提示", "未提供删除功能，敬请期待")

        server_feedback_data = ServerFeedbackController().all_info()
        self.common_data(edit, server_feedback_data, self.window.treeWidget_4, delete_func=window_delete)
    def show_score_data(self):
        """积分管理"""
        def edit(fd, sd):
            data = ScoreController().get_info((fd, sd))
            edit_score_window(self, data)

        def window_delete(fd, sd):
            print("我被触发啦")
            QMessageBox.information(self.window, "提示", "未提供删除功能，敬请期待")

        score_data = ScoreController().all_info()
        self.common_data(edit, score_data, self.window.treeWidget_5, delete_func=window_delete)

    def common_data(self, window_edit, data, TreeWidget, delete_func=None):
        """数据展示复用函数"""
        def edit(f_data, s_data):
            print(f"该行第一个数据为{f_data}，该行第二个数据为{s_data}")
            window_edit(f_data, s_data)

        def confirm_delete(f_data, s_data):
            reply = QMessageBox.question(
                self.window,
                "确认",
                "是否确定执行此操作？",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            if reply == QMessageBox.Yes:
                print(f"该行第一个数据为{f_data}，该行第二个数据为{s_data}")
                if delete_func:
                    delete_func(f_data, s_data)  # 调用外部传入的删除函数
                print("已删除该条数据")
            else:
                print("取消操作成功")

        TreeWidget.clear()  # 清除之前数据
        row_id = 1
        for row in data:
            first_col = row[0]
            second_col = row[1]
            item = QTreeWidgetItem(TreeWidget)
            col_idx = 1
            for text in row:
                item.setText(0, str(row_id))
                item.setText(col_idx, str(text))
                col_idx += 1

            # 创建按钮和布局
            button_layout = QHBoxLayout()
            edit_button = QPushButton("编辑")
            delete_button = QPushButton("删除")
            edit_button.clicked.connect(lambda _, fc=first_col, sc=second_col: edit(fc, sc))
            if delete_func:
                delete_button.clicked.connect(lambda _, fc=first_col, sc=second_col: confirm_delete(fc, sc))
            button_layout.addWidget(edit_button)
            button_layout.addWidget(delete_button)
            button_layout.setContentsMargins(0, 0, 0, 0)

            # 创建 QWidget 作为容器
            button_container = QWidget()
            button_container.setLayout(button_layout)
            TreeWidget.setItemWidget(item, col_idx, button_container)

            row_id += 1
